package com.yang.core.plugins.monitoring;

import com.yang.core.model.ExceptionContext;
import com.yang.core.model.RequestContext;
import com.yang.core.model.ResponseContext;
import com.yang.core.api.RestClientInterceptor;
import com.yang.core.config.RestClientProperties;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 性能监控拦截器
 */
@Slf4j
public class PerformanceMonitoringInterceptor implements RestClientInterceptor {

    private final RestClientProperties.Monitoring monitoringConfig;
    private final ConcurrentHashMap<String, Long> totalResponseTimes = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, AtomicLong> requestCounts = new ConcurrentHashMap<>();

    public PerformanceMonitoringInterceptor(RestClientProperties.Monitoring monitoringConfig) {
        this.monitoringConfig = monitoringConfig;
    }

    @Override
    public void preRequest(RequestContext context) {
        // 记录请求开始时间
        context.setAttribute("startTime", System.currentTimeMillis());
    }

    @Override
    public void postResponse(ResponseContext context) {
        Long startTime = (Long) context.getAttribute("startTime");
        if (startTime != null) {
            long responseTime = System.currentTimeMillis() - startTime;
            String endpoint = "endpoint"; // 简化处理

            totalResponseTimes.compute(endpoint, (k, v) -> v == null ? responseTime : v + responseTime);
            requestCounts.computeIfAbsent(endpoint, k -> new AtomicLong(0)).incrementAndGet();

            long requestCount = requestCounts.get(endpoint).get();
            long averageResponseTime = totalResponseTimes.get(endpoint) / requestCount;

            log.debug("性能指标 - 端点: {}, 响应时间: {}ms, 平均响应时间: {}ms, 请求次数: {}",
                    endpoint, responseTime, averageResponseTime, requestCount);

            // 如果响应时间超过阈值（设置为5秒），记录警告
            long threshold = 5000; // 5秒阈值，可配置化
            if (responseTime > threshold) {
                log.warn("慢响应警告 - 端点: {}, 响应时间: {}ms, 阈值: {}ms",
                        endpoint, responseTime, threshold);
            }
        }
    }

    @Override
    public void onError(ExceptionContext context) {
        String endpoint = context.getUrl().substring(context.getUrl().lastIndexOf('/') + 1);
        log.debug("性能监控 - 端点: {}, 发生异常: {}", endpoint, context.getException().getClass().getSimpleName());
    }

    private String extractEndpoint(RequestContext request) {
        // 简单的端点提取逻辑，可以根据需要改进
        String url = request.getUrl();
        return url.substring(url.lastIndexOf('/') + 1);
    }

    /**
     * 获取平均响应时间
     */
    public long getAverageResponseTime(String endpoint) {
        Long totalTime = totalResponseTimes.get(endpoint);
        AtomicLong count = requestCounts.get(endpoint);

        if (totalTime == null || count == null || count.get() == 0) {
            return 0;
        }

        return totalTime / count.get();
    }

    /**
     * 获取总响应时间
     */
    public long getTotalResponseTime(String endpoint) {
        return totalResponseTimes.getOrDefault(endpoint, 0L);
    }

    /**
     * 重置性能统计
     */
    public void reset() {
        totalResponseTimes.clear();
        requestCounts.clear();
        log.debug("性能监控统计已重置");
    }
}